/*
* 2018/03/12
* 购物车抛物线动画
* */

(function () {
    function fly(options, callback) {
        this.startX = options.start.x || 0                      // 起始横坐标
        this.startY = options.start.y || 0                      // 起始纵坐标
        this.endX = options.end.x || 0                          // 结束横坐标
        this.endY = options.end.y || 0                          // 结束纵坐标
        this.initialSpeed = 0                                   // 初速度
        this.duration = 0                                       // 运动总时长
        this.x = 0                                              // 运动时的实时横坐标
        this.y = 0                                              // 运动时的实时纵坐标
        this.moveX = 0                                          // 在横坐标方向的总运动距离
        this.moveY = 0                                          // 在纵坐标方向的总运动距离
        this.gravity = options.gravity || 1580                  // 纵坐标方向的加速度
        this.t = 0                                              // 实时运动时间
        this.timer = null                                       // 定时器对象
        this.dom = null                                         // 运动的dom对象
        this.callback = callback || null

        this.fling()
    }

    fly.prototype = {
        constructor: fly,
        computePosition: function () {
            this.moveX = this.endX - this.startX
            this.moveY = this.endY - this.startY
            this.initialSpeed = this.moveX * Math.pow((this.gravity / (2 * this.moveY)), 0.5)
            this.duration = this.moveX / this.initialSpeed
        },
        createDom: function () {
            this.dom = document.createElement('span')
            this.dom.style.position = 'fixed'
            this.dom.style.left = this.startX + 'px'
            this.dom.style.top = this.startY + 'px'
            this.dom.style.width = '10px'
            this.dom.style.height = '10px'
            this.dom.style.borderRadius = '10px'
            this.dom.style.backgroundColor = 'red'
            this.dom.style.zIndex = '9999'
            document.body.appendChild(this.dom)
        },
        fling: function () {
            var self = this

            this.createDom()
            this.computePosition()
            this.timer = setInterval(function () {
                self.t += 0.01
                self.x = self.t * self.initialSpeed + self.startX
                self.y = 0.5 * self.gravity * Math.pow(self.t, 2) + self.startY
                self.dom.style.left = self.x + 'px'
                self.dom.style.top = self.y + 'px'

                if (self.y >= self.endY || self.t >= self.duration) {
                    document.body.removeChild(self.dom)
                    clearInterval(self.timer)
                    if (self.callback) {
                        self.callback()
                    }
                }
            }, 10)
        }
    }

    window.fly = fly
})()